const fs = require('fs')
const path = require('path')
const Mock = require('mockjs')
const _ = require('lodash')
const moment = require('moment')
const Redis = require('ioredis')
const uuidv1 = require('uuid/v1')
const settings = require('../../settings')
const redis = new Redis({
  port: 6379, // Redis port
  host: '127.0.0.1', // Redis host
  prefix: 'Information_Youth:', // 存诸前缀
  ttl: 60 * 60 * 23, // 过期时间
  family: 4,
  db: 0
})
moment.locale('zh-cn')

const ipRegex = new RegExp(
  'http://[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}:[0-9]{1,5}',
  'g'
)

function getTime() {
  return (function() {
    return _.now()
  })()
}

function changeSize(size, type) {
  let result = size
  switch (type) {
    case 'k':
      result = size / 1024
      break
    case 'm':
      result = size / 1024 / 1024
      break
    default:
      break
  }
  return result
}

function createDirSync(dirname) {
  if (fs.existsSync(dirname)) {
    return true
  } else {
    // 开始递归调用函数,并接受其返回值:
    const recResult = createDirSync(path.dirname(dirname))
    if (recResult) {
      fs.mkdirSync(dirname)
      return true
    }
  }
}
function upImg(file, filePath, time) {
  const reader = fs.createReadStream(file.path)
  const fileResource = filePath + `/${time}.jpg`
  const upstream = fs.createWriteStream(fileResource)
  reader.pipe(upstream)
  return true
}

function upNewsImg(file) {
  const uuid = uuidv1()
  const today = moment().format('YYYY/MM/DD')
  const filePath = `${settings.PATH__UPLOAD__NEWS}/${today}`
  if (createDirSync(filePath)) {
    if (upImg(file, filePath, uuid)) {
      return `${today}/${uuid}.jpg`
    }
  }
}

function upAvatarImg(file) {
  const uuid = uuidv1()
  const today = moment().format('YYYY/MM/DD')
  const filePath = `${settings.PATH__UPLOAD__AVATAR}/${today}`
  if (createDirSync(filePath)) {
    if (upImg(file, filePath, uuid)) {
      return `${today}/${uuid}.jpg`
    }
  }
}

function codeEqual(code1 = '', code2 = '') {
  if (_.isNull(code1) || _.isNull(code2)) {
    return false
  }
  if (code1.toLowerCase().trim() === code2.toLowerCase().trim()) {
    return true
  }
  return false
}

function getClientIp(req) {
  try {
    return (
      req.headers['x-forwarded-for'] ||
      req.headers['x-real-ip'] ||
      req.headers['x-wq-realip'] ||
      req.connection.remoteAddress ||
      req.socket.remoteAddress ||
      req.connection.socket.remoteAddress
    )
  } catch (e) {
    // logger.info('getClientIp error')
    // return ''
  }
}

Mock.defaultObject = {
  status: 200,
  data: {
    statu: 0
  }
}

module.exports = {
  getTime,
  changeSize,
  upNewsImg,
  upAvatarImg,
  codeEqual,
  moment,
  redis,
  getClientIp,
  Mock,
  settings,
  ipRegex
}
